package top.zerozoo.learn.grade.dao.impl;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import top.zerozoo.learn.grade.dao.StudentDao;
import top.zerozoo.learn.grade.entity.Student;
import top.zerozoo.learn.grade.util.JdbcUtils;

import java.util.List;

public class StudentDaoImpl implements StudentDao {

    private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());

    @Override
    public int count() {
        final String sql = "select count(*) from student";
        return template.queryForObject(sql, Integer.class);
    }

    @Override
    public int countByMajorID(int id) {
        final String sql = "select count(*) from student where majorID = ?";
        return template.queryForObject(sql, Integer.class, id);
    }

    @Override
    public Student findById(int id) {
        final String sql = "select * from student where id = ?";
        Student result;
        try {
            result = template.queryForObject(sql, new BeanPropertyRowMapper<>(Student.class), id);
        } catch (IncorrectResultSizeDataAccessException ex) {
            return null;
        }
        return result;
    }
    

    @Override
    public List<Student> findByMajorID(int id, int start, int rows) {
        final String sql = "select * from student where majorID = ? limit ?,?";
        List<Student> result = template.query(sql, new BeanPropertyRowMapper<>(Student.class), id, start, rows);
        return result;
    }

    @Override
    public int insert(Student student) {
        final String sql = "insert into student(name,birthday,sex,address,phone,idcard,majorID) values(?,?,?,?,?,?,?)";
        return template.update(sql,
                student.getName(),
                student.getBirthday(),
                student.getSex(),
                student.getAddress(),
                student.getPhone(),
                student.getIdcard(),
                student.getMajorID());
    }

    @Override
    public int deleteById(int id) {
        final String sql = "delete from student where id = ?";
        return template.update(sql, id);
    }

    @Override
    public int update(Student student) {
        final String sql = "update student set name = ?,birthday = ?,sex = ?,address = ?,phone = ?,idcard = ?,majorID = ? where id = ?";
        return template.update(sql,
                student.getName(),
                student.getBirthday(),
                student.getSex(),
                student.getAddress(),
                student.getPhone(),
                student.getIdcard(),
                student.getMajorID(),
                student.getId());
    }
}
